import settings from "@/settings";
import { getEnterpriseId } from "@/utils/getEnterpriseId";
import UrlFactory from "./urlFactory.js";
import {parseExtStr} from './parseExtStr.js'

export const getAuthenSF = async (goUrl, key) => {
  try {
    const enterpriseId = getEnterpriseId();
    const urlProcessor = UrlFactory.getInstance();

    console.log("进入 getAuthenSF 方法");
    console.log('getAuthenSF------goUrl',goUrl)
    console.log('getAuthenSF------key',key)
    console.log('getAuthenSF------phone'+$nuxt.$store.state["authen/phoneOrigin"]);
    console.log('getAuthenSF------enterpriseId',enterpriseId)

    if (!enterpriseId) {
      alert("请传递站点参数");
      return;
    }
    const originUrl = !!goUrl ? goUrl : urlProcessor.encodeUrlStr();

    // 获取油企信息
    const enterpriseInfo = await $nuxt.$axios.$get("/selectEnterpriseInfo", {
      params: {
        enterpriseId: enterpriseId
      }
    });
    $nuxt.$store.commit("authen/setEnterpriseInfo", enterpriseInfo.data);// 保存油企信息

    // 无openid，先跳转获取openid
    if (!$nuxt.$store.getters["authen/openId"]) {
      console.log("getAuthenSF----我要微信认证了",originUrl); 
      // originUrl 即一开始进入页面的链接  如从扫员工码进来时的链接是:/246/fuel/remit/.stationId_321-stationName_test342-userId_742-utmSource_1
      
      // 获取appid
      $nuxt.$store.dispatch("authen/getAppId", enterpriseId).then((res) => {
        sessionStorage.setItem("enterpriseId", enterpriseId);
        $nuxt.$store.commit("authen/setEnterpriseId", enterpriseId);
          if (enterpriseInfo.data["gzhAppSecret"] != undefined) {
            console.log('有密钥--老版本授权')
            // 老版本授权
            window.location.href =
              "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
              $nuxt.$store.getters["authen/appId"] +
              "&redirect_uri=" +
              settings.baseUrl +
              "remitAuthSF&response_type=code&scope=snsapi_base&state=" +
              originUrl +
              "#wechat_redirect";
              
          } else {
            // 新版本授权
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${$nuxt.$store.getters["authen/appId"]}&redirect_uri=${settings.baseUrl}remitAuthSF&response_type=code&scope=snsapi_base&state=${originUrl}&component_appid=${settings.componentAppid}#wechat_redirect`;
          }
      }).catch((error) => {
        alert(error+'失败')
      })
      return; 
    }
      console.log('getAuthenSF-------originUrl--------',originUrl)
      /** 
       * 获取用户信息(后端在这个接口会根据openId来判断，如果数据库没有openId则会创建一个用户信息)
       * 返回值： consumerId， nickName， mobilePhone，enterpriseId，enterpriseName
       * mobilePhone： 如果完全新用户，手机号是空的，如果已经领了会员卡的话，是有手机号的 
       * **/ 
    const res = await $nuxt.$axios.$get('/getOrCreateUserInfo',{
        params:{
          enterpriseId:$nuxt.$store.getters['authen/enterpriseId'],
          openId:$nuxt.$store.getters['authen/openId'],
          nickName:''
        }
      })
      const info ={
        ...res.data,
        enterpriseId:res.data.enterprise.enterpriseId,
        enterpriseName:res.data.enterprise.enterpriseName
      }
      $nuxt.$store.commit('authen/setUserInfo',info)
      $nuxt.$store.commit('authen/setConsumerId',res.data.consumerId)
    
      let urlInfo = parseExtStr(originUrl)
      // 直接跳转到支付页面 remitSF.vue
      let url = `/${urlInfo.enterpriseId}/fuel/remitSF/?stationId=${urlInfo.searchObj.stationId}&stationName=${urlInfo.searchObj.stationName}&userId=${urlInfo.searchObj.userId}&utmSource=${urlInfo.searchObj.utmSource}`
      window.location.href = url 
    
  } catch (e) {
    const msg = !!e.message ? e.message : e;
    alert(msg);
  }
};
